import passport from '@/assets/passport.png';
import signal from '@/assets/traffic.png';
import origin from '@/assets/origin.png';
import end from '@/assets/end.png';
import stop from '@/assets/station.png';
const icon = {
    passport:{
        url: passport,
        size: [24,24]
    },
    trafficSignal:{
        url: signal,
        size: [22,10]
    },
    origin:{
        url: origin,
        size: [25,40]
    },
    end:{
        url: end,
        size: [25,40]
    },
    stop:{
        url: stop,
        size: [32,32]
    },
}

let loadedScripts = [];

// 初始化
const importAMap = async function(){
    return await new Promise((resolve)=>{
        if (loadedScripts.includes('amap')) {
            resolve();
        } else {
            let script = document.createElement('script');
            script.src ='https://webapi.amap.com/maps?v=1.4.13&key=ac2aa06389621e08b8c5fb0b63c95f53';
            document.body.appendChild(script);
            script.onload = function () {
                loadedScripts.push('amap');
                resolve();
            };
        }
    });
}

// 点
function AMarker(position,title,icon){
    let x = icon.size[0];
    let y = icon.size[1];
    return new AMap.Marker({
        position: position,
        title: title,
        icon: new AMap.Icon({
            image: icon.url,
            size:new AMap.Size(x,y),
            imageSize:new AMap.Size(x,y)
        }),
        offset: new AMap.Pixel(-0.5*x,-1*y)
    })
}
// 线
function ALine(data,color){
    let lineArr = []
    data.forEach(item =>{
        let polyline = new AMap.Polyline({
            path:change(item.coordinates),
            strokeColor:color,
            cursor:'pointer',
            title:item.RoadName || '无名',
            extData:{
                name:item.RoadName,
                id:item.ID
            }
        })
        lineArr.push(polyline)
    })
    let overlayGroup = new AMap.OverlayGroup(lineArr)
    overlayGroup.on('click',(e)=>{
        const {id,name}=e.target.B.extData
        e.target.setOptions({strokeColor:'skyblue',strokeWeight:4})
        console.log('line',id,name)
    })
    return overlayGroup
}

// 面
function polygon(path){
    return new AMap.Polygon({
        path: path,
        strokeColor: "#F45B5B", 
        strokeWeight: 3,
        strokeOpacity: 0.9,
        strokeStyle: "dashed",
        fillOpacity: 0,
        fillColor: '#1791fc',
        zIndex: 50,
    })
}
// 面的集合
function polygonArr(data,fillColor){
    let arr = [];
    data.forEach((item)=>{
        const path =  buildChange(item.coord)
        let polygon = new AMap.Polygon({
            path: path,
            strokeColor: "#F45B5B", 
            strokeWeight: 1,
            strokeOpacity: 0.9,
            fillOpacity: 0.8,
            fillColor: fillColor,
            cursor:'pointer',
            // zIndex:20
        });
        polygon.on('click',()=>{
            console.log('test')
        })
        arr.push(polygon);
    })
    return arr;
}
// 集合
function AInfowindow(map,position,content,icon){
    let y = icon.size[1]
    map.setCenter(position);
    let infoWindow = new AMap.InfoWindow({
        content:content,
        offset:new AMap.Pixel(0,-1*y)
    })
    infoWindow.open(map,position)
}
// 卡口
function passports(map,data){
    let arr = [];
    data.forEach(item => {
        new Promise(reslove=>{
            AMap.convertFrom([item.lng,item.lat],"gps",(status,result)=>{
                if(result.info==="ok"){
                    let lnglats = result.locations;
                    reslove(lnglats)
                }
            })
        }).then(res=>{
            let marker = AMarker(res[0],item.name,icon.passport)
            marker.on("click",(e)=>{
                let position = e.target.getPosition();
                let content = e.target.getTitle();
                AInfowindow(map,position,content,icon.passport)
            })
            arr.push(marker)
        })
    });
    return arr
}
// 信号灯
function trafficSignal(map,data){
    let arr = [];
    data.forEach(item=>{
        let position = item.point.split(',')
        let marker = AMarker(position,item.name,icon.trafficSignal)
        arr.push(marker)
    })
    let markerLayer = new AMap.OverlayGroup(arr)
    markerLayer.on("click",(e)=>{
        let position = e.target.getPosition();
        let content = e.target.getTitle();
        AInfowindow(map,position,content,icon.trafficSignal)
    })
    return markerLayer
}
// 公交线路
function busRoutes(map,data){
    map.plugin("AMap.Transfer",()=>{
        let route = new AMap.Transfer({
            policy: AMap.TransferPolicy.LEAST_TIME,
            city: '东莞市',
            nightflag: true,
            // map:map,
            hideMarkers:true,
        })
        let busRotue = []
        data.forEach((item,index)=>{
            if(index< data.length-1){
                route.search(data[index],data[index+1],(status, result) => {
                    if(status === 'complete'){
                        // console.log("打印路线",result)
                        result.plans[0].segments.map((item)=>{
                            if(item.transit_mode === 'BUS'){
                                // console.log("bus路线",item.transit.path)
                                busRotue = busRotue.concat(item.transit.path)
                                // let line = new AMap.Polyline({
                                //     path: item.transit.path,
                                //     isOutline: true,
                                //     outlineColor: '#ffeeee',
                                //     borderWeight: 2,
                                //     strokeWeight: 5,
                                //     strokeColor: '#0091ff',
                                //     lineJoin: 'round',
                                //     strokeStyle: 'solid',
                                //     lineCap:'round',
                                //     // bubble:true,
                                //     // showDir:true,
                                //     cursor:"pointer"
                                // })
                                // line.on("click",(e)=>{
                                //     console.log("测试",e.target)
                                //     let infoWindow = new AMap.InfoWindow({
                                //         content:"test",
                                //     })
                                //     e.target.setOptions({showDir:true})
                                //     infoWindow.open(map,e.lnglat)
                                // })
                                // line.setMap(map)
                            }
                        })
                    }
                })
            }
        })
        console.log(busRotue);
        return busRotue;
        // route.search(start[1],end[1],(status, result) => {
        //     if(status === 'complete'){
        //         console.log("打印路线2",result)
        //     }
        // })
        // route2.search(start[1],end[1],{waypoints:pass2})
    })
}
// 公交站点
function busStation(data){
    let markerArr = [];
    let lnglatArr = [];
    data.forEach(item=>{
        item.stations.forEach(sub=>{
            new Promise(reslove=>{
                AMap.convertFrom([sub.lng,sub.lat],"gps",(status,result)=>{
                    if(result.info === 'ok'){
                        var lnglats = result.locations;
                        lnglatArr.push(lnglats[0]);
                        reslove(lnglats[0])
                    }
                })
            }).then(res=>{
                let marker = AMarker(res,sub.stationName,icon.stop)
                markerArr.push(marker);
            })
        })
    })
    return { markerArr, lnglatArr };
}

// 文本
function text(){
    return new AMap.Text({
        text:"测试-纯文本标记1",
        draggable:true,
        style:{
            "background":"transparent",
            "border-width":0,
        },
        zooms:[13,18],
        position:[113.870836, 23.109164]
    })
}
// 格式转换
function change(data){
    var coordArr = []
    data.split("|").forEach(item=>{
        coordArr.push(item.split(";").map(Number))
    })
    return coordArr
}
function buildChange(data){
    var coordArr = []
    data.split(";").forEach(item=>{
        coordArr.push(item.split(",").map(Number))
    })
    return coordArr
}

export {
    importAMap,
    point,
    passports,
    trafficSignal,
    busRoutes,
    busStation,
    polyline,
    ALine,
    polygon,
    polygonArr,
    text,
    change
}